﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Word = Microsoft.Office.Interop.Word;
using System.Windows.Forms;
using LTM_Extra;
using System.ComponentModel;
using System.Text.RegularExpressions;
using Microsoft.Office.Core;

namespace LTM_Main
{

    class Helper
    {
        public static void InitTableLayoutPanel(TableLayoutPanel tableLayout, IList<Variable> propertyNames)
        {
            tableLayout.ColumnCount = 2;
            tableLayout.RowCount = 0;
            tableLayout.Controls.Clear();
            foreach (var item in propertyNames)
            {
                tableLayout.RowCount++;
                Label lbl = item.GetLableControl();
                lbl.Size = new System.Drawing.Size(200, 20);

                Control control = item.GetContentControl();
                
             
                tableLayout.Controls.Add(lbl, 0, tableLayout.RowCount - 1);
                tableLayout.Controls.Add(control, 1, tableLayout.RowCount - 1);
                
            }

        }

        public static IDictionary<string, string> GetPropertiesFromTableLayout(TableLayoutPanel tableLayout)
        {
            IDictionary<string, string> properties = new Dictionary<string, string>();
            foreach (var control in tableLayout.Controls)
            {
                TextBox txtbox = control as TextBox;
                if (txtbox != null)
                {
                    properties.Add(txtbox.Name.Remove(0, 3), txtbox.Text);
                }
                ComboBox cmb = control as ComboBox;
                if (cmb != null && cmb.SelectedValue!=null)
                {
                    properties.Add(cmb.Name.Remove(0, 3), cmb.SelectedValue.ToString());
                }

            }
            return properties;

        }

        public static void ApplyVariablesToTemplate(object templatePath,IDictionary<string,string> variables )
        {
           
            Word.Document currentDoc=null;
            foreach (Word.Document item in Globals.ThisAddIn.Application.Documents)
            {
                currentDoc = item;
            }
            Object missing = Type.Missing;
            Word.Document   doc = Globals.ThisAddIn.Application.Documents.Add(ref templatePath, ref missing,ref missing,ref missing);
            //GetStylesFromTemplate(doc);

           
             foreach (Word.HeaderFooter header in GetHeaderFooters(true))
            {
                string txt = header.Range.Text;

                foreach (Word.Field item in header.Range.Fields)
                {
                    string key = item.Code.Text.Trim();
                    
                    if (!variables.ContainsKey(key))
                    {
                       
                        continue;
                    }
                    item.Select();
                    Globals.ThisAddIn.Application.Selection.TypeText(variables[key]);
                }
             }



                foreach (Word.HeaderFooter footer in GetHeaderFooters(false))
                {
                    foreach (Word.Field item in footer.Range.Fields)
                    {
                        string key = item.Code.Text.Trim();
                        
                        if (!variables.ContainsKey(key))
                        {

                            continue;
                        }
                        item.Select();
                        Globals.ThisAddIn.Application.Selection.TypeText(variables[key]);
                    }
                    
                }

            

              
                foreach (Word.Field item in doc.Fields)
                {
                    string key = item.Code.Text.Trim();
                    
                    if (!variables.ContainsKey(key))
                    {
                       // MessageBox.Show("Not pre-defined variable:" + key);
                        continue;
                    }
                    item.Select();
                    Globals.ThisAddIn.Application.Selection.TypeText(variables[key]);
                }
                if (currentDoc != null)
                {
                    object saveChange=false;
                    currentDoc.Close(ref saveChange,ref missing,ref missing);
                }
           
          
        

        }


        private static IList<Word.HeaderFooter> GetHeaderFooters(bool isHeader)
        {
            IList<Word.HeaderFooter> headerFootersList = new List<Word.HeaderFooter>();

            Word.Document doc = Globals.ThisAddIn.Application.ActiveDocument;

            foreach (Word.Section section in doc.Sections)
            {
                Word.HeadersFooters headerFooters = null;
                if (isHeader)
                {
                    headerFooters = section.Headers;
                }
                else
                {
                    headerFooters = section.Footers;
                }

                foreach (Word.HeaderFooter headerFooter in headerFooters)
                {
                    headerFootersList.Add(headerFooter);
                }
            }

            return headerFootersList;
 
        }



        public static void HideLogo()
        {
            
                foreach (Word.HeaderFooter header in GetHeaderFooters(true))
                {
                    
                    foreach (Word.InlineShape shape in header.Range.InlineShapes)
	                {
                       
                        shape.ConvertToShape().Visible =  MsoTriState.msoFalse;
                       
                		 
	                }
                  

                }


        }

        public static void ShowLogo()
        {

            foreach (Word.HeaderFooter header in GetHeaderFooters(true))
            {

                foreach (Word.InlineShape shape in header.Range.InlineShapes)
                {

                    shape.ConvertToShape().Visible = MsoTriState.msoCTrue;


                }

                foreach (Word.Shape shape in header.Shapes)
                {

                    shape.Visible = MsoTriState.msoCTrue;
                    shape.ConvertToInlineShape();


                }


            }




        }

        public static void HideFooter()
        {
            foreach (Word.HeaderFooter header in GetHeaderFooters(false))
            {

                foreach (Word.InlineShape shape in header.Range.InlineShapes)
                {

                    shape.ConvertToShape().Visible = MsoTriState.msoFalse;


                }


            }
        }

        public static void ShowFooter()
        {
            foreach (Word.HeaderFooter header in GetHeaderFooters(false))
            {

                foreach (Word.InlineShape shape in header.Range.InlineShapes)
                {

                    shape.ConvertToShape().Visible = MsoTriState.msoCTrue;


                }

                foreach (Word.Shape shape in header.Shapes)
                {

                    shape.Visible = MsoTriState.msoCTrue;
                    shape.ConvertToInlineShape();


                }


            }
        }

        public static void ShowCompanyAddress(ContentProvider provider)
        {
            foreach (Word.HeaderFooter header in GetHeaderFooters(true))
            {
                foreach (Word.Paragraph paragraph in header.Range.Paragraphs)
                {
                    Word.Style style = (Word.Style)paragraph.get_Style();

                    if (style != null && style.NameLocal == provider.GetAppSettings(Constants.StyleHideAddress))
                    {
                        object showAddressStyle = provider.GetAppSettings(Constants.StyleShowAddress);
                        paragraph.set_Style(ref showAddressStyle);
                    }

                    if (style != null && style.NameLocal == provider.GetAppSettings(Constants.StyleHideCompany))
                    {
                        object showCompanyStyle =provider.GetAppSettings( Constants.StyleShowCompany);
                        paragraph.set_Style(ref showCompanyStyle);
                    }
                }
            
            }

        
        }
        public static void HideCompanyAddress(ContentProvider provider)
        {
            foreach (Word.HeaderFooter header in GetHeaderFooters(true))
            {
                foreach (Word.Paragraph paragraph in header.Range.Paragraphs)
                {
                    Word.Style style = (Word.Style)paragraph.get_Style();

                    if (style != null && style.NameLocal == provider.GetAppSettings(Constants.StyleShowAddress))
                    {
                        object hideAddressStyle =provider.GetAppSettings( Constants.StyleHideAddress);
                        paragraph.set_Style(ref hideAddressStyle);
                    }

                    if (style != null && style.NameLocal == provider.GetAppSettings(Constants.StyleShowCompany))
                    {
                        object hideCompanyStyle =provider.GetAppSettings( Constants.StyleHideCompany);
                        paragraph.set_Style(ref hideCompanyStyle);
                    }
                }

            }
        
        }


        public static IDictionary<string, Style> GetStylesFromTemplate(ContentProvider provider)
        {
          //  List<Style> styleList = new List<Style>();
            //Style name format:[H1_Master Title] Product Sheet
          
            IDictionary<string, Style> tempStyles = new Dictionary<string, Style>();
            foreach (Word.Style wordStyle in Globals.ThisAddIn.Application.ActiveDocument.Styles)
            {


                if (Regex.IsMatch(wordStyle.NameLocal, Constants.StyleNameRegExp))
                {
                    string[] fullyName=wordStyle.NameLocal.Remove(0,1).Split(new Char[]{']'}, StringSplitOptions.RemoveEmptyEntries)[0].Split(new Char[]{'_'});
                    string name= fullyName[0];
                    string description=fullyName[1];


                    var style = new Style();
                    style.WordStyle = wordStyle;
                    style.Discription = description;
                    style.FriendlyName = name;
                    style.Name = wordStyle.NameLocal;
                    tempStyles.Add(wordStyle.NameLocal, style);
                }
            }

            return tempStyles;
        }

        public static void ApplyStyleToSelection(object style)
        {
           
            Globals.ThisAddIn.Application.ActiveDocument.ActiveWindow.Selection.Range.set_Style(ref style);
        }


        public static void InitTableLayoutPanelControlsValue(TableLayoutPanel tableLayout, IDictionary<string, string> keyValuePairs)
        {
            foreach (KeyValuePair<string, string> item in keyValuePairs)
            {

                var txtControls = tableLayout.Controls.Find(Constants.TextBoxPrefix + item.Key, true);
                var cmbControls = tableLayout.Controls.Find(Constants.ComBoxPrefix + item.Key, true);
                if (txtControls.Count() == 0 && cmbControls.Count() == 0)
                {
                    continue;
                }
                if (txtControls.Count() > 0)
                {
                    txtControls[0].Text = item.Value;
                }
                if (cmbControls.Count() > 0)
                {
                    ComboBox cmb = cmbControls[0] as ComboBox;
                    if (cmb.Items.Count > 0)
                    {

                        cmb.SelectedIndex = ((IEnumerable<string>)cmb.DataSource).ToList().IndexOf(item.Value);
                    }
                }
            }

        }

      
             
    }

   
}
